<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 具体页面结构 -->

      <PageTools>
        <template #left>总记录数:20条</template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <!-- 自定义指令来实现按钮级别的权限控制 -->
          <!-- v-if="$store.state.user.userInfo.roles.points.includes('export')" -->
          <!-- v-allow是我们自己定义的指令。
          他的作用是：只有当vuex中保存的权限有export时，这个元素才被可见 -->
          <el-button
            v-allow="'export'"
            type="danger"
            size="small"
            @click="hExportExcel"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="hAdd"
          >新增员工</el-button>
        </template>
      </PageTools>
      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop: 'workNumber'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="scope">
              <!-- 额外的图片组件 -->
              <!-- <img :src="scope.row.staffPhoto"> -->
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>

          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template v-slot="scope">{{ formatType(scope.row.formOfEmployment) }}</template>
          </el-table-column>

          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!--
            @current-change: 用户点击了页码

          -->
          <el-pagination
            layout="total, sizes, prev, pager, next"
            :page-size="size"
            :current-page.sync="page"
            :page-sizes="[3, 5, 10, 20]"
            :total="total"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>

    <!-- 添加 -->
    <el-dialog title="添加" :visible.sync="showDialog">

      <EmpDialog
        v-if="showDialog"
        @success="hSuccess"
        @close="hClose"
      />
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="showDialogRole">
      <AssignRole
        v-if="showDialogRole"
        :cur-employee-id="curId"
        @success="hSuccessRole"
      />
    </el-dialog>
  </div>
</template>

<script>
import EmployeENUM from '@/constant/employees'
const EMPLOYTYPE = EmployeENUM.hireType.reduce((acc, cur) => { acc[cur.id] = cur.value; return acc }, {})
console.log(EmployeENUM.hireType, EMPLOYTYPE)
import { getEmployees, delEmployee } from '@/api/employees.js'
import EmpDialog from './empDialog.vue'
import AssignRole from './assignRole'

export default {
  components: { EmpDialog, AssignRole },
  data() {
    return {
      showDialog: false, // 添加员工的弹出框
      showDialogRole: false, // 分配角色的弹框
      size: 5, // 每页几条数据
      page: 1, // 当前显示的页码
      total: 0, // 总共几条数据
      list: [],
      curId: ''// 当前被选中的员工的id
    }
  },
  created() {
    // 请求部门信息
    this.loadEmployees()
  },
  methods: {
    hSuccessRole() {
      // 关闭弹窗
      this.showDialogRole = false
    },
    // 用户点击了分配角色
    hAssignRole(id) {
      this.showDialogRole = true
      // 保存id 便于父传子
      this.curId = id
    },
    // 添加新员工
    hSuccess() {
      this.showDialog = false
      // 跳转到最后一页去看数据
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployees()
    },
    hClose() {
      this.showDialog = false
    },
    hAdd() {
      this.showDialog = true
    },
    async doDel(id) {
      // 调用API
      await delEmployee(id)

      // 如果删除是最后一条数据，则页码要-1
      if (this.list.length === 1) {
        let page = this.page
        page--
        // 页码不能减是0
        page = Math.max(1, page)
        this.page = page
      }
      // 重发请求
      this.loadEmployees()
      // 提示一下
      this.$message.success('删除成功')
    },
    hDel(id) {
      // 确认框
      this.$confirm('是否要删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除操作
        this.doDel(id)
      }).catch(() => {

      })
    },
    // 用户点击了页码
    hCurrentChange(curPage) {
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployees()
    },
    // 用户切换了 每页几条
    hSizeChange(curSize) {
      console.log(curSize)
      // 1. 更新每页几条 - 统一让他求第一页
      this.page = 1
      this.size = curSize
      // 2. 重发请求
      this.loadEmployees()
    },
    // formatType(1)  ===> 正式
    // formatType(2)  ===> 非正式
    formatType(typeId) {
      return EMPLOYTYPE[typeId] || '未知'
    },
    async loadEmployees() {
      const res = await getEmployees({ page: this.page, size: this.size })

      // 保存数据
      this.list = res.data.rows

      this.total = res.data.total
    }
  }
}

</script>
